class Solution {
public:
    int dx[4]={0,0,1,-1};
    int dy[4]={1,-1,0,0};
    vector<vector<bool>> vecFlg;
    bool dfs(int x,int y,vector<vector<char>>& board, string& word,int pos){

        if(pos>=word.size()){
            return true;
        }
        int n=board.size(),m=board[0].size();
        for(int i=0;i<4;++i){
            int nx=x+dx[i];
            int ny=y+dy[i];
            if(nx<0 || nx>=n || ny<0 || ny>=m || vecFlg[nx][ny] || word[pos]!=board[nx][ny]){
                continue;
            }
            vecFlg[nx][ny]=true;
            if(dfs(nx,ny,board,word,pos+1)){
                return true;
            }
            vecFlg[nx][ny]=false;
        }

        return false;
    }
    bool exist(vector<vector<char>>& board, string word) {
        
        int n=board.size(),m=board[0].size();
        vecFlg=vector<vector<bool>> (n,vector<bool>(m));
        for(int i=0;i<n;++i){
            for(int j=0;j<m;++j){
                if(board[i][j]==word[0]){
                    vecFlg[i][j]=true;
                    if(dfs(i,j,board,word,1)){
                        return true;
                    }
                    vecFlg[i][j]=false;
                }
            }
        }
        
        return false;
    }
};
